<?php
/**
 * +----------------------------------------------------------------------+
 * php23种设计模式实现-状态模式
 * Author：微信公众号：yuantanphp
 * 获取更多资源，技术答疑，项目合作请关注微信公众号：yuantanphp
 * +----------------------------------------------------------------------+
 */
namespace State;
//顾客类
class Customer{
    private $_name;         //顾客名称
    private $_state;        //状态
    private $_consumption;  //销售额
    public function __construct($name)
    {
        $this->_name = $name;
    }
    //设置顾客状态
    public function setState($state){
        $this->_state = $state;
    }
    //设置销售额
    public function setConsumption($consumption){
        $this->_consumption = $consumption;
    }
    //获取顾客花费
    public function getConsumption(){
        return $this->_consumption;
    }
    public function getName(){
        return $this->_name;
    }
    //开始打折
    public function discount(){
        return $this->_state->discount($this);
    }
}
//状态类
interface State
{
    public function discount($customer);
}
//优惠方案A
class DiscountPlanA implements State{
    public function discount($customer)
    {
        if ($customer->getConsumption() >= 15000) {
            return 0.70;
        } else {
            $customer->SetState(new DiscountPlanB());
            return $customer->discount();
        }
    }
}
//优惠方案B
class DiscountPlanB implements State{
    public function discount($customer)
    {
        if ($customer->getConsumption() >= 11000) {
            return 0.80;
        } else {
            $customer->SetState(new DiscountPlanC());
            return $customer->discount();
        }
    }
}
//优惠方案C
class DiscountPlanC implements State{
    public function discount($customer)
    {
        return 0.90;
    }
}
$customer = new Customer("叶先生");
$customer->setState(new DiscountPlanA); //初始化优惠方案A
$customer->setConsumption(11000);
echo "顾客 ".$customer->getName()." 消费：".$customer->getConsumption()." 并享受：".$customer->discount()
." 折扣"." 实际应付：".$customer->getConsumption() * $customer->discount()."<br />";
$customer = new Customer("冯先生");
$customer->setState(new DiscountPlanA); //初始化优惠方案A
$customer->setConsumption(16000);
echo "顾客 ".$customer->getName()." 消费：".$customer->getConsumption()." 并享受：".$customer->discount()
." 折扣"." 实际应付：".$customer->getConsumption() * $customer->discount()."<br />";
$customer = new Customer("马先生");
$customer->setState(new DiscountPlanA); //初始化优惠方案A
$customer->setConsumption(8000);
echo "顾客 ".$customer->getName()." 消费：".$customer->getConsumption()." 并享受：".$customer->discount()
." 折扣"." 实际应付：".$customer->getConsumption() * $customer->discount();
